package com.ruoyi.web.controller.shop;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ImsYzzcSunBranch;
import com.ruoyi.common.core.domain.entity.SysCityData;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.IImsYzzcSunBranchService;
import com.ruoyi.system.service.ISysCityDataService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 门店信息管理
 * 
 * @author ruoyi
 * @date 2024-03-18
 */
@RestController
@RequestMapping("/shop/branch")
public class ImsYzzcSunBranchController extends BaseController
{
    @Autowired
    private IImsYzzcSunBranchService imsYzzcSunBranchService;

    @Autowired
    private ISysCityDataService sysCityDataService;

    public static final Logger log = LoggerFactory.getLogger(ImsYzzcSunBranchController.class);

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询门店列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(ImsYzzcSunBranch imsYzzcSunBranch)
    {
        startPage();
        return getDataTable(imsYzzcSunBranchService.selectImsYzzcSunBranchList(imsYzzcSunBranch));
    }

    /**
     * 导出门店列表
     */
    @Log(title = "门店", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ImsYzzcSunBranch imsYzzcSunBranch)
    {
        Long userId = SecurityUtils.getUserId();
        if(userId!=1){
            imsYzzcSunBranch.setUniacid(userId);
        }
        List<ImsYzzcSunBranch> list = imsYzzcSunBranchService.selectImsYzzcSunBranchList(imsYzzcSunBranch);
        ExcelUtil<ImsYzzcSunBranch> util = new ExcelUtil<ImsYzzcSunBranch>(ImsYzzcSunBranch.class);
        util.exportExcel(response, list, "门店数据");
    }

    /**
     * 获取门店详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        if (ObjectUtils.isNotEmpty(id))
        {
            ImsYzzcSunBranch imsYzzcSunBranch=imsYzzcSunBranchService.selectImsYzzcSunBranchById(id);
            ajax.put(AjaxResult.DATA_TAG, imsYzzcSunBranch);
            ajax.put("areaCity",new Long[]{imsYzzcSunBranch.getProvince(),imsYzzcSunBranch.getCity(),imsYzzcSunBranch.getArea()});
        }
        return ajax;
    }

    /**
     * 新增门店
     */
    @PreAuthorize("@ss.hasPermi('stores:branch:add')")
    @Log(title = "门店", businessType = BusinessType.INSERT)
    @PostMapping
    @Anonymous
    public AjaxResult add(@RequestBody ImsYzzcSunBranch imsYzzcSunBranch)
    {
        SysUser user = null;
        try {
            user = SecurityUtils.getLoginUser().getUser();
            if (user != null) {
                imsYzzcSunBranch.setUniacid(user.getUserId());
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (ObjectUtils.isNotEmpty(imsYzzcSunBranch.getAreaCity())){
                Long[] areaCity = imsYzzcSunBranch.getAreaCity();
                if (areaCity.length > 2) {
                    imsYzzcSunBranch.setProvince(areaCity[0]);
                    imsYzzcSunBranch.setCity(areaCity[1]);
                    imsYzzcSunBranch.setArea(areaCity[2]);
                }
            }
            SysDept dept = new SysDept();
            if (user != null && user.getDeptId() != null) {
                dept.setParentId(user.getDeptId());
                dept.setDeptName(imsYzzcSunBranch.getName());
                dept.setStatus("0");
                dept.setDelFlag("0");
                deptService.insertDept(dept);
            }
            imsYzzcSunBranch.setCreatetime(DateUtils.getNowDate());
            imsYzzcSunBranch.setDeptId(dept.getDeptId());
            int rows = imsYzzcSunBranchService.insertImsYzzcSunBranch(imsYzzcSunBranch);
            return toAjax(rows);
        }
    }

    /**
     * 修改门店
     */
    @PreAuthorize("@ss.hasPermi('stores:branch:update')")
    @Log(title = "门店", businessType = BusinessType.UPDATE)
    @PutMapping
    @Anonymous
    public AjaxResult edit(@RequestBody ImsYzzcSunBranch imsYzzcSunBranch)
    {
        if (ObjectUtils.isNotEmpty(imsYzzcSunBranch.getAreaCity())){
            imsYzzcSunBranch.setProvince(imsYzzcSunBranch.getAreaCity()[0]);
            imsYzzcSunBranch.setCity(imsYzzcSunBranch.getAreaCity()[1]);
            imsYzzcSunBranch.setArea(imsYzzcSunBranch.getAreaCity()[2]);
        }
        return toAjax(imsYzzcSunBranchService.updateImsYzzcSunBranch(imsYzzcSunBranch));
    }

    /**
     * 删除门店
     */
    @PreAuthorize("@ss.hasPermi('stores:branch:delete')")
    @Log(title = "门店", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @Anonymous
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int num=0;
        for(int i=0;i<ids.length;i++){
            SysUser sysUser=new SysUser();
            sysUser.setShopIds(ids[i] + "");
            List<SysUser> sysUserList= userService.selectUserList(sysUser);
            if (ObjectUtils.isNotEmpty(sysUserList)){
                num++;
            }
        }
        if(num>0){
            return error("选中的店铺中存在有用户的店铺,无法删除");
        }else{
            return toAjax(imsYzzcSunBranchService.deleteImsYzzcSunBranchByIds(ids));
        }
    }

    /**
     * 门店照片上传
     */
    @Log(title = "门店照片", businessType = BusinessType.UPDATE)
    @PostMapping("/upload/file")
    @Anonymous
    public AjaxResult avatar(@RequestParam("shopfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            String vehicle = FileUploadUtils.upload(RuoYiConfig.getShopPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", vehicle);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 查询省市区列表
     */
    @GetMapping("/dataCityList")
    @Anonymous
    public AjaxResult dataCityList(SysCityData sysCityData)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysCityData> cityDataList = sysCityDataService.selectCityDataList(sysCityData);
        ajax.put(AjaxResult.DATA_TAG, cityDataList);
        return ajax;
    }

    /**
      *  计算用户与门店之前的距离
       * @return 米
     */
     public static double getDistance(double userLng, double userLat, double shopLng, double shopLat) {
         // 维度
         double lat1 = (Math.PI / 180) * userLat;
         double lat2 = (Math.PI / 180) * shopLat;
         // 经度
         double lon1 = (Math.PI / 180) * userLng;
         double lon2 = (Math.PI / 180) * shopLng;
         // 地球半径
         double R = 6371;
         // 两点间距离 km，如果想要米的话，结果*1000就可以了
         double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
         return d * 1000;
     }

}
